package itbour.onetouchshow;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.google.gson.Gson;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.utils.HttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import itbour.onetouchshow.activity.version1_3.MainActivityV3;
import itbour.onetouchshow.bean.PhoneDevInfoBean;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.DeviceUtil;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;

/**
 * Created by Administrator on 2017/3/24.
 */

public class ExceptionCrashHander implements Thread.UncaughtExceptionHandler {
    private static ExceptionCrashHander mException;
    private String TAG = "tag";
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Context mContext;
    //public static boolean isException=false;

    private ExceptionCrashHander() {
//        Cockroach.install(new Cockroach.ExceptionHandler() {
//            // handlerException内部建议手动try{  你的异常处理逻辑  }catch(Throwable e){ } ，以防handlerException内部再次抛出异常，导致循环调用handlerException
//            @Override
//            public void handlerException(final Thread thread, final Throwable throwable) {
//                new Handler(Looper.getMainLooper()).post(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            upLoadService(throwable);
//                            // Log.d("Cockroach", thread + "\n" + throwable.toString());
//                            throwable.printStackTrace();
//                            L_.e(throwable.getMessage());
//                            //Toast.makeText(App.this, "Exception Happend\n" + thread + "\n" + throwable.toString(), Toast.LENGTH_SHORT).show();
////                        throw new RuntimeException("..."+(i++));
//                        } catch (Throwable e) {
//                            L_.e(throwable.getMessage());
//                            upLoadService(throwable);
//                        }
//                    }
//                });
//            }
//        });
//
//        Cockroach.uninstall();

    }

    public static ExceptionCrashHander getInstance() {
        if (mException == null) {
            synchronized (ExceptionCrashHander.class) {
                if (mException == null) {
                    mException = new ExceptionCrashHander();
                }
            }
        }
        return mException;
    }

    /**
     * Cell phone information
     *
     * @return
     */
    public static String getMobileInfo() {
        StringBuffer sb = new StringBuffer();
        try {
            Field[] fields = Build.class.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                String value = field.get(null).toString();
                sb.append(name + "=" + value);
                sb.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public void init(Context context) {
        this.mContext = context;
        // isException=false;
        Thread.currentThread().setUncaughtExceptionHandler(this);
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread t, Throwable ex) {
        Log.e("TAG", "到拦截闪退信息");
        //isException=true;
        // 1. 获取信息
        // 1.1 崩溃信息
        // 1.2 手机信息
        // 1.3 版本信息
        // 2.写入文件
        String crashFileName = saveInfoToSD(ex);
        upLoadService(ex);
        L_.e(TAG, "fileName --> " + crashFileName);
        //fileName --> /data/data/com.example.myapplication/files/crash/2017_03_24_20_24.txt

        // 3. 缓存崩溃日志文件
        cacheCrashFile(crashFileName);
        //重启应用
        Intent intent = new Intent(mContext, MainActivityV3.class);
        @SuppressLint("WrongConstant")
        PendingIntent restartIntent = PendingIntent.getActivity(
                mContext, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        //退出程序
        AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 300,
                restartIntent); // 1秒钟后重启应用
        // 杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());

        // 系统默认处理
        mDefaultHandler.uncaughtException(t, ex);


    }

    public void upLoadService(Throwable ex) {
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        String appVersionName = DeviceUtil.getAppVersionName(UIUtils.getContext());
        //手机型号
        String model = Build.MODEL;
        //系统版本
        String release = Build.VERSION.RELEASE;
        PhoneDevInfoBean phoneDevInfoBean = new PhoneDevInfoBean(model, release, appVersionName);
        String deviceInfo = new Gson().toJson(phoneDevInfoBean);
        stringStringHashMap.put("device", AppConst.ANDROID_DEVICE + "");
        // stringStringHashMap.put("uuid", "EEBAF7D1EC6914A914CE95209D6BFDBB-Android");
        stringStringHashMap.put("deviceInfo", deviceInfo);
        stringStringHashMap.put("errorLog", ex.getMessage());
        HttpUtils.getInstance().executeGet(AppConfig.UPLOADAPPERRLOG_V1_0, stringStringHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                // mvpView.loadFaild(exception);
                L_.e("exception" + exception);
            }

            @Override
            protected void onSuccess(String response) {
                L_.e("exception" + response);

            }
        });
    }

    /**
     * 缓存崩溃日志文件
     *
     * @param fileName
     */
    private void cacheCrashFile(String fileName) {
        SharedPreferences sp = mContext.getSharedPreferences("crash", Context.MODE_PRIVATE);
        sp.edit().putString("CRASH_FILE_NAME", fileName).commit();
    }

    /**
     * 获取崩溃文件名称
     *
     * @return
     */
    public File getCrashFile() {
        String crashFileName = mContext.getSharedPreferences("crash",
                Context.MODE_PRIVATE).getString("CRASH_FILE_NAME", "");
        return new File(crashFileName);
    }

    /**
     * 保存获取的 软件信息，设备信息和出错信息保存在SDcard中
     *
     * @param ex
     * @return
     */
    private String saveInfoToSD(Throwable ex) {
        String fileName = null;
        StringBuffer sb = new StringBuffer();

        for (Map.Entry<String, String> entry : obtainSimpleInfo(mContext).entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key).append(" = ").append(value).append("\n");
        }

        sb.append(obtainExceptionInfo(ex));

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File dir = new File(AppCache.getInstance().mException + File.separator + "crash"
                    + File.separator);

            // 先删除之前的异常信息
            if (dir.exists()) {
                deleteDir(dir);
            }

            // 再从新创建文件夹
            if (!dir.exists()) {
                dir.mkdir();
            }
            try {
                fileName = dir.toString()
                        + File.separator
                        + getAssignTime("yyyy_MM_dd_HH_mm") + ".txt";
                FileOutputStream fos = new FileOutputStream(fileName);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    /**
     * 返回当前日期根据格式
     **/
    private String getAssignTime(String dateFormatStr) {
        DateFormat dataFormat = new SimpleDateFormat(dateFormatStr);
        long currentTime = System.currentTimeMillis();
        return dataFormat.format(currentTime);
    }

    /**
     * 获取一些简单的信息,软件版本，手机版本，型号等信息存放在HashMap中
     *
     * @return
     */
    private HashMap<String, String> obtainSimpleInfo(Context context) {
        HashMap<String, String> map = new HashMap<>();
        PackageManager mPackageManager = context.getPackageManager();
        PackageInfo mPackageInfo = null;
        try {
            mPackageInfo = mPackageManager.getPackageInfo(
                    context.getPackageName(), PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        map.put("versionName", mPackageInfo.versionName);
        map.put("versionCode", "" + mPackageInfo.versionCode);
        map.put("MODEL", "" + Build.MODEL);
        map.put("SDK_INT", "" + Build.VERSION.SDK_INT);
        map.put("PRODUCT", "" + Build.PRODUCT);
        map.put("MOBLE_INFO", getMobileInfo());
        return map;
    }

    /**
     * 获取系统未捕捉的错误信息
     *
     * @param throwable
     * @return
     */
    private String obtainExceptionInfo(Throwable throwable) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        throwable.printStackTrace(printWriter);
        printWriter.close();
        return stringWriter.toString();
    }


    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful. If a
     * deletion fails, the method stops attempting to delete and returns
     * "false".
     */
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            // 递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return true;
    }

}
